package com.atguigu.gmall.order.api;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.order.model.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: 小兰
 * @Date: 2023/5/6 20:50
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 汇总渲染订单确认页面所选的数据
     * @param request
     * @return
     */
    @GetMapping("/auth/trade")
    public Result orderTrade(HttpServletRequest request){
        String userId1 = AuthContextHolder.getUserId(request);
        Long userId = Long.valueOf(userId1);
        Map<String,Object> mapResult =  orderInfoService.trade(userId);
        return Result.ok(mapResult);
    }

    /**
     * 提交订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(HttpServletRequest request,@RequestBody OrderInfo orderInfo
            ,@RequestParam("tradeNo") String tradeNo){
        //前端需要拿orderinfoId,去跳转页面,所以业务层要返回订单id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.valueOf(userId));
        Long orderId= orderInfoService.submitOrder(orderInfo,tradeNo);
        return Result.ok(orderId);
    }
    /**
     * 查询我的订单列表
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result getOrderList(HttpServletRequest request,@PathVariable("page") Long page,
                               @PathVariable("limit") Long limit){
        Page<OrderInfo> infoPage = new Page<>(page,limit);
        //获取当先用户ID
        String userId = AuthContextHolder.getUserId(request);
        infoPage = orderInfoService.getOrderList(infoPage,userId);
        return Result.ok(infoPage);
    }

    /**
     * 根据订单ID查询订单信息 包含订单明细
     * @param orderId
     * @return
     */
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfoById(@PathVariable("orderId") Long orderId){
        return orderInfoService.getOrderInfoById(orderId);
    }
}
